package cn.itbox.example.application.controller;

import cn.itbox.uap.util.http.OkHttpExtUtil;
import cn.itbox.uap.util.http.factory.ItBoxOkHttpClientFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

/**
 * @CreateTime: 2024-02-21  10:17
 * @Version: 1.0
 * @Author: huyanbing
 */
@Slf4j
@RestController
@RequestMapping("/ok/https")
public class OkHtttpsTestController {


    @Resource
    private OkHttpExtUtil okHttpExtUtil;


    @GetMapping
    public String list() {

        String url = "https://sandbox.99bill.com:7445/umgw/common/distribute.html";
        String body = "{\"head\":{\"memberCode\":\"10012932671\",\"messageType\":\"M0001\",\"version\":\"1.0.0\",\"externalRefNumber\":\"20240221101149_0b19e\"},\"requestBody\":{\"signedData\":\"a3caa15e-26a5-4a90-829b-6e4596f79f07\",\"envelopedData\":\"92280ee7-460e-4e71-a295-b659092f0e57\"}}";
        Map<String, String> headers = new HashMap<>();
        headers.put("okhttp-test", "1");
        String res = okHttpExtUtil.post(url, body, headers, 1000L);

        System.out.printf(res);

        return res;
    }


    public static void main(String[] args) {

        String certPath="D:\\workspace\\workspace2024\\02\\springboot-study\\springboot-study-application\\src\\main\\resources\\certs\\ssl\\sandbox.ssl.pfx";

        try (InputStream inputStream = new FileInputStream(certPath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                System.out.write(buffer, 0, bytesRead);
            }


            KeyStore  keyStore = KeyStore.getInstance("PKCS12");
            String password = "123456";
            keyStore.load(inputStream, password.toCharArray());


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static InputStream getCertFileStream(String certPath) {
        try {
            if (certPath.startsWith("classpath:")) {
                String path = certPath.substring("classpath:".length());
                return ItBoxOkHttpClientFactory.class.getClassLoader().getResourceAsStream(path);
            } else {
                return new FileInputStream(new File(certPath));
            }
        } catch (FileNotFoundException var2) {
            log.error("文件读取错误，地址为：{}", certPath);
            throw new RuntimeException("文件读取错误，地址为：" + certPath);
        }
    }
}
